<template>
	<div :id="id" :class="className" :style="{ height: height, width: width }"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
	props: {
		className: {
			type: String,
			default: 'chart',
		},
		id: {
			type: String,
			default: 'pieChart',
		},
		width: {
			type: String,
			default: '200px',
		},
		height: {
			type: String,
			default: '200px',
		},
		chartData: {
			type: Object,
		},
	},
	data() {
		return {
			chart: null,
		}
	},
	created() {
		// console.log(this.chartData)
	},
	mounted() {
		this.initChart()
		// console.log(this.chartData)
		if (this.chartData) {
			this.setChartOptions(this.chartData)
		}
	},
	beforeDestroy() {
		if (!this.chart) {
			return
		}
		this.chart.dispose()
		this.chart = null
	},
	methods: {
		initChart() {
			this.chart = echarts.init(document.getElementById(this.id))
			// this.chart.setOption({
			// 	title: {
			// 		text: '某站点用户访问来源',
			// 		top: '3%',
			// 		left: '3%',
			// 	},
			// 	tooltip: {
			// 		trigger: 'item',
			// 		formatter: '{a} <br/>{b} : {c} ({d}%)',
			// 	},
			// 	series: [
			// 		{
			// 			name: '访问来源',
			// 			type: 'pie',
			// 			top: '2%',
			// 			bottom: '8%',
			// 			radius: '55%',
			// 			center: ['50%', '60%'],
			// 			data: [
			// 				{ value: 335, name: '直接访问' },
			// 				{ value: 310, name: '邮件营销' },
			// 				{ value: 234, name: '联盟广告' },
			// 				{ value: 135, name: '视频广告' },
			// 				{ value: 1548, name: '搜索引擎' },
			// 			],
			// 		},
			// 	],
			// })
		},
		setChartOptions(data) {
			// console.log(data)
			let optionsdata = data
			// 基础配置
			let options = {}
			options.title = {
				text: optionsdata.title,
				top: '3%',
				left: '3%',
				textStyle: {
					color: '#fff',
					fontWeight: 'normal',
					fontSize: '16',
				},
			}
			options.tooltip = {
				trigger: 'item',
				formatter: '{a} <br/>{b} : {c} ({d}%)',
			}
			let seriesArr = []
			let serieObj = {
				name: '统计',
				type: 'pie',
				top: '3%',
				bottom: '8%',
				radius: '55%',
				center: ['50%', '60%'],
				label: {
					formatter: '{b}: {c}',
				},
				data: optionsdata.data,
			}
			seriesArr.push(serieObj)
			options.series = seriesArr
			this.chart.setOption(options)
		},
	},
	watch: {
		chartData() {
			// console.log(this.chartData)
			this.setChartOptions(this.chartData)
		},
	},
}
</script>
